package com.mxz.common.core.utils;

import com.mxz.common.core.constant.CommConstants;
import com.mxz.common.core.utils.snowflake.Snowflake;

/**
 * 生成唯一code
 * @author mxz
 * @date 2021/10/20
 */
public class CodeUtils {

    private static Snowflake snowflake;

    /**
     * 获取环境变量工作机器ID [0,31]
     */
    private static String WORKER_ID = System.getProperty("workerId");

    /**
     * 生成用户的编码code
     * @return
     */
    public static String buildUserCode(){
        return BaseConvertUtil.toBase36(getCode());
    }

    /**
     * 生成店铺的编码code
     * @return
     */
    public static synchronized String buildShopCode(){
        return BaseConvertUtil.toBase36(System.currentTimeMillis());
    }

    /**
     * 生成订单的编号
     * @return
     */
    public static String buildOrderNo(){
        return addNoPrefix(CommConstants.ORDER_PR);
    }

    /**
     * 生成订单的编号
     * @param: prefix
     * @return
     */
    public static String buildOrderNo(String prefix){
        return addNoPrefix(prefix);
    }

    /**
     * 编号添加前缀
     * @return
     */
    private static String addNoPrefix(String prefix){
        if(StringUtils.isEmpty(prefix)){
            return getCode().toString();
        }
        return prefix+getCode();
    }

    /**
     * 通过雪花算法的获取编号
     * @return
     */
    private static Long getCode(){
        if (StringUtils.isNotNull(snowflake)) {
            return snowflake.nextId();
        }
        //用来获取系统变量 工作机器ID[0,31]
        if(StringUtils.isEmpty(WORKER_ID)){
            snowflake = new Snowflake(1L,1L);
        }else{
            snowflake = new Snowflake(1L,Long.valueOf(WORKER_ID));
        }
        return snowflake.nextId();
    }

    public static void main(String[] args) {
        System.out.println(buildShopCode());
    }
}
